package com.gree.elasticsearch.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gree.elasticsearch.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 总有刁民想害朕，请叫我小花狗
 * create by zxw on 2020/5/27
 */
@Component
public class LocalAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private Logger logger = LoggerFactory.getLogger(LocalAuthenticationEntryPoint.class);

    private Http403ForbiddenEntryPoint http403ForbiddenEntryPoint = new Http403ForbiddenEntryPoint();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String authenticationMessage = authException.getMessage();
        logger.debug("user need authentication, and authentication exception message is {}", authenticationMessage);
        PrintWriter printWriter = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        printWriter.write(objectMapper.writeValueAsString(ResponseUtil.unAuthentication()));
        printWriter.flush();
        printWriter.close();
    }
}
